<script setup>
// import {ref} from "vue";
import {onMounted, reactive, ref} from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/util/http-util.js'
import { useRouter } from 'vue-router'
import apps from '@/config/application.js'

const isRegister = ref(false)
const codeUrl = ref("");
const lock = ref(false);
const randCode = ()=>{
  if (lock.value){
    return
  }
  lock.value = true;
  codeUrl.value =  http.randomCode()
  setTimeout(()=>{
    lock.value = false;
  },1000)
}

const loginData = ref({
  phone: '',
  code:'',
  password: '',
})

const checkLogin = ()=>{
  http.GET("/getUser").then((rep)=>{
    if (rep.code == 0){
      router.push("/profile");
    }else {
      randCode();
    }
  })
}


onMounted(()=>{
  //检查登陆
  checkLogin();
})
const registerData = ref({
  username: '',
  phone: '',
  sex:1,
  password: '',
  rePassword: '',
})

// 密码校验
const passwordValidator = (rule, value, callback) => {
  if (value == '') {
    callback(new Error('请再次输入密码'))
    // 响应式数据要先.value
  } else if (registerData.value.password != value) {
    callback(new Error(`两次输入密码不同`))
  } else {
    callback()
  }
  return
}


const router = useRouter()

const register = async () => {
  registerData.value.username = registerData.value.username.trim()
  registerData.value.password = registerData.value.password.trim()
  registerData.value.rePassword = registerData.value.rePassword.trim()
  if (registerData.value.password !=  registerData.value.rePassword){
    ElMessage.error("两次密码不一致，重新输入！");
    return;
  }
  // 发送注册请求
  http.POST("/register",registerData.value).then((response) => {
    if (response.code == 0) {
      ElMessage.success("注册成功")
      isRegister.value = false;
    }
  })

  // ElMessage.success("注册成功")
}

const options = ref([
  {
    value: 1,
    label: '男',
  },
  {
    value: 2,
    label: '女',
  }
])


const onSubmit = async () => {
  try {

    // 假设这是你的登录API端点
    http.POST("/login",loginData.value).then((response) => {
      if (response.code == 0) {
        ElMessage.success("登录成功")
        if (response.data.role == 'manage'){
          router.push("/room")
        }else {
          router.push("/consume")
        }
      }
    })


  } catch (error) {
    // 请求出错，显示错误信息
    ElMessage.error("请求错误")
  }
}

const bgList = ref([
  {
    url:'/zxs1.jpg',
    desc: '简约风自习室'
  },
  {
    url:'/zxs2.jpg',
    desc: '原木风自习室'
  },
  {
    url:'/zxs3.jpeg',
    desc: '企业级自习室'
  }
])

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度为6-16位', trigger: 'blur' },
  ],
  rePassword: [
    {
      required: true,
      validator: passwordValidator,
      message: '两次输入密码不同',
      trigger: 'blur',
    },
  ],
}



</script>
<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 左侧轮播图 -->
      <div class="carousel-section">
        <img src="/sdd.png" alt="轮播图" class="carousel-image">
      </div>

      <!-- 右侧表单区域 -->
      <div class="form-section">
        <div class="form-container">
          <div class="form-header">
            <h1>{{ apps.name }}</h1>
          </div>

          <!-- 注册表单 -->
          <el-form
            v-if="isRegister"
            :rules="rules"
            :model="registerData"
            ref="form"
            class="login-form"
          >
            <h2 class="form-title">用户注册</h2>
            
            <el-form-item prop="phone">
              <el-input
                v-model="registerData.phone"
                prefix-icon="Phone"
                placeholder="请输入手机号码"
              />
            </el-form-item>

            <el-form-item prop="sex">
              <el-select
                v-model="registerData.sex"
                placeholder="请选择性别"
                class="w-full"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerData.password"
                prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>

            <el-form-item prop="rePassword">
              <el-input
                v-model="registerData.rePassword"
                prefix-icon="Lock"
                type="password"
                placeholder="请再次输入密码"
                show-password
              />
            </el-form-item>

            <el-button type="primary" @click="register" class="submit-btn">
              注册账号
            </el-button>

            <div class="form-footer">
              <span>已有账号？</span>
              <el-link type="primary" @click="isRegister = false">返回登录</el-link>
            </div>
          </el-form>

          <!-- 登录表单 -->
          <el-form
            v-else
            :rules="rules"
            :model="loginData"
            ref="form"
            class="login-form"
          >
            <h2 class="form-title">欢迎登录</h2>

            <el-form-item prop="phone">
              <el-input
                v-model="loginData.phone"
                prefix-icon="Phone"
                placeholder="请输入手机号码"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginData.password"
                prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>

            <el-form-item prop="code" class="captcha-item">
              <el-input
                v-model="loginData.code"
                prefix-icon="Key"
                placeholder="请输入验证码"
              />
              <img 
                :src="codeUrl" 
                @click="randCode"
                class="captcha-image"
              />
            </el-form-item>

            <el-button type="primary" @click="onSubmit" class="submit-btn">
              登录
            </el-button>

            <div class="form-footer">
              <span>还没有账号？</span>
              <el-link type="primary" @click="isRegister = true">立即注册</el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 1000px;
  height: 600px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

.carousel-section {
  flex: 1;
  position: relative;
}

.carousel-item {
  height: 100%;
}

.carousel-content {
  position: relative;
  height: 100%;
}

.carousel-image {
  width: 500px;
  height: 500px;
  object-fit: cover;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.2), rgba(0,0,0,0.6));
  z-index: 1;
}

.carousel-text {
  position: absolute;
  bottom: 60px;
  left: 40px;
  right: 40px;
  color: #fff;
  z-index: 2;
}

.carousel-text h2 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.carousel-text p {
  font-size: 16px;
  opacity: 0.9;
}

.form-section {
  width: 450px;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: #fff;
}

.form-container {
  width: 100%;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
}

.form-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.form-title {
  font-size: 20px;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.captcha-item {
  display: flex;
  gap: 12px;
}

.captcha-item :deep(.el-form-item__content) {
  display: flex;
  gap: 12px;
}

.captcha-image {
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  margin-top: 10px;
  border-radius: 22px;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  color: #606266;
}

.w-full {
  width: 100%;
}

@media (max-width: 768px) {
  .login-container {
    width: 100%;
    height: auto;
    flex-direction: column;
  }

  .carousel-section {
    display: none;
  }

  .form-section {
    width: 100%;
    padding: 30px 20px;
  }
}
</style>
